import { Promise } from 'drunk-base';
import { notEmpty } from '../../../../service/Validator';
import { observable, computed } from 'mobx';
import { getPage, createPage, updatePage } from './PageHttpResource';
import { getAdsOptionsByName } from '../../../assets/standard/AdsHttpResource';
import { getEventOptionsByName } from '../../../assets/standard/EventHttpResource';
import { getTopicOptionsByName } from '../../../assets/standard/TopicHttpResource';
import { getBannerOptionsByName } from '../../../assets/standard/BannerHttpResource';
import { ItemModel, IItemProps, Validate } from '../../../ItemModel';
import { IMeitiInfo } from "../../../Meiti";

export interface IStandarPageModel extends IItemProps {
    title: string; // 页面标题
    shareTitle: string; // 分享标题
    shareDesc: string; // 分享文案
    logo: string; // logo图
    categories: ICategory[];
    meiti?: IMeitiInfo;
}

export interface ICategory {
    name: string; // 分类名称
    ads: ICategoryOptions;
    topics: ICategoryOptions[];
    events: ICategoryOptions[];
    banners: ICategoryOptions[];
}

export interface ICategoryOptions {
    id: string;
    name: string;
}

export class StandardPageModel extends ItemModel<IStandarPageModel> {

    @observable data: IStandarPageModel = {
        title: "",
        shareDesc: "",
        shareTitle: "",
        logo: "",
        categories: [
            {
                name: "",
                ads: { name: "", id: "" },
                banners: [{ name: "", id: "" }],
                topics: [{ name: "", id: "" }],
                events: [{ name: "", id: "" }]
            }
        ]
    };

    @Validate(`请输入页面标题`)
    @computed get titleValid() { return notEmpty(this.data.title) }

    @Validate(`请输入分享标题`)
    @computed get shareTitleValid() { return notEmpty(this.data.shareTitle) }

    @Validate(`请输入分享文案`)
    @computed get shareDescValid() { return notEmpty(this.data.shareDesc) }

    @Validate(`请上传一张页面LOGO图片`)
    @computed get logoValid() { return notEmpty(this.data.logo) }

    @Validate(`分类不能多于4个且名称不能为空`)
    @computed get categoriesValid() {
        return this.data.categories.length >= 1 &&
            this.data.categories.length <= 4 &&
            this.data.categories.every(category => notEmpty(category.name));
    }

    @observable adsOptions: ICategoryOptions[] = [];
    @observable eventOptions: ICategoryOptions[] = [];
    @observable topicOptions: ICategoryOptions[] = [];
    @observable bannerOptions: ICategoryOptions[] = [];

    private timerIds = { ads: null, events: null, topics: null, banners: null };

    createItemImpl(data: IStandarPageModel) {
        return createPage(data);
    }

    fetchItemImpl(id: string) {
        return getPage(id);
    }

    updateItemImpl(id: string, data: IStandarPageModel) {
        return updatePage(id, data);
    }

    addCategory(position: number) {
        if (this.data.categories.length === 4) {
            return;
        }
        this.data.categories.splice(position, 0, {
            name: "",
            ads: { name: "", id: "" },
            topics: [{ name: "", id: "" }],
            events: [{ name: "", id: "" }],
            banners: [{ name: "", id: "" }],
        });
    }

    deleteCategory(position: number) {
        this.data.categories.splice(position, 1);
    }

    updateAds(categoryIndex: number, id: string) {
        this.data.categories[categoryIndex].ads = this.adsOptions.filter(options => id === options.id)[0];
    }

    addBanner(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].banners.splice(position, 0, { name: "", id: "" });
    }

    updateBanner(categoryIndex: number, position: number, id: string) {
        let options = this.bannerOptions.filter(options => options.id === id)[0];
        this.data.categories[categoryIndex].banners[position] = options;
    }

    deleteBanner(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].banners.splice(position, 1);
    }

    addTopic(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].topics.splice(position, 0, { name: "", id: "" });
    }

    updateTopic(categoryIndex: number, position: number, id: string) {
        let options = this.topicOptions.filter(options => options.id === id)[0];
        this.data.categories[categoryIndex].topics[position] = options;
    }

    deleteTopic(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].topics.splice(position, 1);
    }

    addEvent(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].events.splice(position, 0, { name: "", id: "" });
    }

    updateEvent(categoryIndex: number, position: number, id: string) {
        let options = this.eventOptions.filter(options => options.id === id)[0];
        this.data.categories[categoryIndex].events[position] = options;
    }

    deleteEvent(categoryIndex: number, position: number) {
        this.data.categories[categoryIndex].events.splice(position, 1);
    }

    fetchAdsOptions(name: string) {
        clearTimeout(this.timerIds.ads);
        this.timerIds.ads = setTimeout(() => {
            getAdsOptionsByName(name).then(res => {
                this.adsOptions = res;
            });
        }, 300);
    }

    fetchBannerOptions(name: string) {
        clearTimeout(this.timerIds.banners);
        this.timerIds.banners = setTimeout(() => {
            getBannerOptionsByName(name).then(res => {
                this.bannerOptions = res;
            });
        }, 300);
    }

    fetchEventOptions(name: string) {
        clearTimeout(this.timerIds.events);
        this.timerIds.events = setTimeout(() => {
            getEventOptionsByName(name).then(res => {
                this.eventOptions = res;
            });
        }, 300);
    }

    fetchTopicOptions(name: string) {
        clearTimeout(this.timerIds.topics);
        this.timerIds.topics = setTimeout(() => {
            getTopicOptionsByName(name).then(res => {
                this.topicOptions = res;
            });
        }, 300);
    }

    save(indexOfNeedValidateCategory?: number) {
        if (indexOfNeedValidateCategory != null) {
            let categoryValidResult = this.validateCategory(indexOfNeedValidateCategory);
            if (!categoryValidResult.success) {
                return Promise.reject(categoryValidResult);
            }
        }

        return super.save();
    }

    validateCategory(index: number) {
        let success = false;
        let message = "";
        let category = this.data.categories[index];

        if (!category) {
            message = `分类[${index}]不存在`;
        }
        else if (!(category.events.length >= 4 && category.events.every(event => notEmpty(event.id)))) {
            message = `请至少选择4个活动,添加的活动选项不能留空`;
        }
        else {
            success = true;
        }
        return { success, message };
    }

}